from celery import shared_task
from django.db.models import Count
from computer.models import Computer, Count_City_Com, Count_Room_Com
from datetime import date

@shared_task
def count_computers_statistics():
    # 获取今天的日期
    today = date.today()
    print(today)

    try:
        # 按城市统计主机数量
        city_counts = Computer.objects.values('city').annotate(count=Count('id'))
        # 创建新的城市统计数据
        city_count_objects = [
            Count_City_Com(
                city=item['city'],
                count=item['count'],
                date=today
            ) for item in city_counts
        ]
        # 如果当天的数据已存在，先删除
        Count_City_Com.objects.filter(date=today).delete()
        Count_City_Com.objects.bulk_create(city_count_objects)
        print(222)
        # 按机房统计主机数量
        room_counts = Computer.objects.values('room').annotate(count=Count('id'))
        # 创建新的机房统计数据
        room_count_objects = [
            Count_Room_Com(
                room=item['room'],
                count=item['count'],
                date=today
            ) for item in room_counts
        ]
        # 如果当天的数据已存在，先删除
        Count_Room_Com.objects.filter(date=today).delete()
        Count_Room_Com.objects.bulk_create(room_count_objects)

        return f"已更新 {len(city_count_objects)} 个城市和 {len(room_count_objects)} 个机房的主机统计数据"
    
    except Exception as e:
        return f"统计任务执行失败: {str(e)}" 